package org.beynet.jsonbinding.parser.types.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.beynet.jsonbinding.parser.JSONParsingException;
import org.beynet.jsonbinding.parser.JSONParsingExceptionUnexpectedChar;
import org.beynet.jsonbinding.parser.types.JSONArray;

public class JSONArrayImpl extends JSONAbstractObject implements JSONArray{
    JSONArrayImpl(String encoding,InputStream is) throws IOException, JSONParsingException {
        super(encoding);
        values = new ArrayList<>();
        state = Object_State.INIT;
        loopContent(is);
    }
    @Override
    public List<Object> getValues() {
        return values;
    }

    private void loopContent(InputStream is) throws IOException, JSONParsingException {
        while (state != Object_State.END) {
            if (state == Object_State.INIT) {
                int r = consumeSpaces(is);
                if (r == ']') {
                    state = Object_State.END;
                } else {
                    state = Object_State.EXPECT_VALUE;
                    next = r;
                }
            }
            if (state == Object_State.EXPECT_VALUE) {
                values.add(readValue(is));
                state = Object_State.EXPECT_END_OR_NEXT;
            }
            if (state == Object_State.EXPECT_END_OR_NEXT) {
                int res;
                if (next != -1) {
                    res = next;
                    next = -1;
                } else {
                    res = consumeSpaces(is);
                }
                if (res == ',') {
                    state = Object_State.EXPECT_VALUE;
                } else if (res == ']') {
                    state = Object_State.END;
                } else {
                    throw new JSONParsingExceptionUnexpectedChar(res);
                }
            }
        }
    }

    private List<Object> values;

}
